package ua.vn.ticket_scanner.network.task.http;

import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import ua.vn.ticket_scanner.network.data.ConnectResult;
import ua.vn.ticket_scanner.network.task.SuperBaseTask;
import ua.vn.ticket_scanner.utils.TPreferenceManager;

/**
 * Created by Ivan on 20.06.13.
 */
public abstract class BaseTask extends SuperBaseTask {

    private static final String TAG = "BaseTask";

    private final String url;
    private final int timeout;

    public BaseTask(boolean isTransport) {
        if (isTransport) {
            url = TPreferenceManager.getInstance().getTransportServerUrl();
        } else {
            url = TPreferenceManager.getInstance().getMainServerUrl();
        }
        timeout = TPreferenceManager.getInstance().getHttpTimeout();
    }

    @Override
    protected ConnectResult doInBackground(Void... voids) {
        Log.i(TAG, "Http: started");

        ConnectResult connectResult = null;

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
        HttpConnectionParams.setSoTimeout(httpParameters, timeout);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

        try {
            makeJSON();
            HttpPost request = makeHttpRequest();
            HttpResponse response = httpClient.execute(request);
            connectResult = getResponseResult(response);

            Log.i(TAG, "Http: complete");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        Log.i(TAG, "Http: finished");
        return connectResult;
    }

    private HttpPost makeHttpRequest() throws UnsupportedEncodingException {
        String json = getJSON().toString();
        Log.i(TAG, "Http: json=" + json);
        StringEntity params = new StringEntity(json);
        HttpPost request = new HttpPost(url);
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        return request;
    }

    private ConnectResult getResponseResult(HttpResponse response) {

        StringBuilder builder = new StringBuilder();
        try {
            InputStream inStream = response.getEntity().getContent();
            BufferedReader bufferedIn = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
            String buffer = "";
            while(buffer != null) {
                buffer = bufferedIn.readLine();
                if(buffer != null)
                    builder.append(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        String result = builder.toString();
        Log.i(TAG, "Http: json=" + result);
        try {
            JSONObject json = new JSONObject(result);
            ConnectResult connectResult = new ConnectResult();
            connectResult.setJSON(json);
            return connectResult;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}
